import 'package:cloud_medicine/components/address_edit&new.dart';
import 'package:cloud_medicine/components/util.dart';
import 'package:flutter/material.dart';

class NewAddress extends StatefulWidget {
  NewAddress({Key key}) : super(key: key);

  @override
  _NewAddressState createState() => _NewAddressState();
}

class _NewAddressState extends State<NewAddress> {
  DateTime lastPopTime;

  TextEditingController addressController = new TextEditingController();
  TextEditingController nameController = new TextEditingController();
  TextEditingController phoneController = new TextEditingController();

  bool _loading = false;

  Future<Null> _init() async {
    setState(() {
      _loading = true;
    });
    await Future.delayed(Duration(milliseconds: 100), () {
      if (mounted) {
        setState(() {
          _loading = false;
        });
      }
    });

    return;
  }

  @override
  void dispose() {
    super.dispose();
    addressController.dispose();
    nameController.dispose();
    phoneController.dispose();
  }

  _saveInfoAndCommit() {
    //TODO:传给后端，返回页面时自动替换新地址
    Navigator.pop(context);
  }

  @override
  void initState() {
    super.initState();
    _init();
  }

  _childLayout() {
    if (_loading) {
      return Center(
        child: Container(
          child: CircularProgressIndicator(),
        ),
      );
    } else {
      return AddressEditAndNew(
        addressController: addressController,
        nameController: nameController,
        phoneController: phoneController,
        saveInfoAndCommit: _saveInfoAndCommit,
        oldaddress: '',
        oldname: '',
        oldphone: '',
        id: 1,
      );
    }
  }

  _popPage() {
    Navigator.pop(context);
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async {
          if (lastPopTime == null ||
              DateTime.now().difference(lastPopTime) > Duration(seconds: 1)) {
            //两次点击间隔超过1秒则重新计时
            lastPopTime = DateTime.now();
            openAlertDialog(context, _popPage, '确认退出编辑，一旦退出，一切将不予保存');
            return new Future.value(false);
          }
          return new Future.value(true);
        },
        child: Scaffold(
          appBar: AppBar(
            title: Text('新建收货地址'),
          ),
          body: _childLayout(),
        ));
  }
}
